package com.glodon.ggzy.core.utils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.glodon.ggzy.core.model.BaseModel;

/**
 * 
 * 
 * Json工具类
 * @author yangjf
 * @since jdk1.6
 * @date 2013-6-17
 *
 */
@SuppressWarnings("deprecation")
public abstract class JsonUtils {

	protected static Logger logger = LoggerFactory.getLogger(JsonUtils.class);

	protected static ObjectMapper objectMapper;
	static {
		objectMapper = new ObjectMapper();
		objectMapper.getDeserializationConfig().set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		objectMapper.getSerializationConfig().set(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
		// 设置日期解析格式
		objectMapper.getSerializationConfig().setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
		objectMapper.getDeserializationConfig().setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
		// enum用toString方法
		objectMapper.getSerializationConfig().set(SerializationConfig.Feature.WRITE_ENUMS_USING_TO_STRING, true);
		objectMapper.getDeserializationConfig().set(DeserializationConfig.Feature.READ_ENUMS_USING_TO_STRING, true);

	}

	public final static String toJsonStr(BaseModel entity) throws IOException {
		return objectMapper.writeValueAsString(entity);
	}

	public final static String strArray2JsonStr(Collection<String> collection) throws IOException {
		return objectMapper.writeValueAsString(collection);
	}

	public final static String boolArray2JsonStr(Collection<Boolean> collection) throws IOException {
		return objectMapper.writeValueAsString(collection);
	}

	public final static <T extends Number> String numberArray2JsonStr(Collection<T> collection) throws IOException {
		return objectMapper.writeValueAsString(collection);
	}

	public final static String toJsonStr(Collection<?> collection) throws IOException {
		return objectMapper.writeValueAsString(collection);
	}

}
